package com.kcsj.dao.User;


import com.kcsj.domain.File;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;
/**
 * @author 胡庆阳
 * 29th Nov. 2020
 */
public class FileDao {
    private static final FileDao fileDao = new FileDao();

    private FileDao() {

    }

    public static FileDao getInstance() {
        return fileDao;
    }

    //上传文件图片
    public Integer add(File file, Connection conn) throws SQLException {
        String sql="insert into file(fileName,filePath)values(?,?)";
        PreparedStatement ptmt=conn.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
        ptmt.setString(1, file.getFileName());
        ptmt.setString(2, file.getFilePath());
        ptmt.executeUpdate();
        ResultSet generatedKeys = ptmt.getGeneratedKeys();
        int id = 0;
        if(generatedKeys.next()){
            id = generatedKeys.getInt(1);
        }
        return id;
    }
    //得到所有数据
    public List<File> findAll(Connection conn) throws SQLException {
        File file =null;
        List<File> files =null;
        files =new ArrayList<>();
        String sql="select * from file";
        PreparedStatement ptmt=conn.prepareStatement(sql);
        ResultSet rs=ptmt.executeQuery();
        while(rs.next()){
            file =new File();
            file.setId(rs.getInt("id"));
            file.setFileName(rs.getString("flieName"));
            file.setFilePath(rs.getString("fliePath"));
            file.setCreateTime(rs.getTimestamp("time").toLocalDateTime());
            files.add(file);
        }
        return files;
    }
    //下载查看文件
    public List<File> find(String context, Connection conn) throws SQLException {
        File file =null;
        List<File> files =null;
        files =new ArrayList<>();
        String sql="select * from file where flieName like '%"+context +"%' or fliePath like '%"+context +"%' or id like '%"+context +"%'";
        PreparedStatement ptmt=conn.prepareStatement(sql);
        ResultSet rs=ptmt.executeQuery();
        while(rs.next()){
            file =new File();
            file.setId(rs.getInt("id"));
            file.setFileName(rs.getString("flieName"));
            file.setFilePath(rs.getString("fliePath"));
            files.add(file);
        }
        return files;
    }

}
